package butines.game.steering.behavior;

import java.util.LinkedList;

import butines.core.math2d.Vector2D;
import butines.game.steering.Vehicle;

public class PriorityCombinationBehavior implements Behavior {

	private LinkedList<AbstractBehavior> behaviors = new LinkedList<AbstractBehavior>();

	private Vehicle owner;
	
	private Vector2D steeringForce = new Vector2D();
	
	public PriorityCombinationBehavior(Vehicle owner) {
		if (owner == null) {
			throw new IllegalArgumentException("Argument 'owner' is null");
		}
		this.owner = owner;
	}

	public Vector2D calculate() {
		steeringForce.set(0, 0);
		for (AbstractBehavior behavior : getBehaviors()) {
			if (behavior.isTurned() == false) {
				continue;
			}
			Vector2D force = behavior.calculate();
			if (accumulateForce(force)) {
				break;
			}
		}
		return steeringForce;
	}

	private boolean accumulateForce(Vector2D force) {
		float magnitudeRemannig = owner.getMaxForce() - steeringForce.length();
		if (magnitudeRemannig <= 0f) {
			return true;
		}
		float magnitudeToAdd = force.length();
		if (magnitudeToAdd < magnitudeRemannig) {
			steeringForce.add(force);
		} else {
			force.normalise();
			force.mult(magnitudeRemannig);
			steeringForce.add(force);
		}
		return false;
	}

	public void addBehavior(AbstractBehavior behavior) {
		behaviors.add(behavior);
	}

	public LinkedList<AbstractBehavior> getBehaviors() {
		return behaviors;
	}
	
}
